package club.xcgame520.okhttp;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/1.
 */

public class SyncOkHttp {

    private OkHttpClient client;

    private Context context;

    public SyncOkHttp(Context context) {
        this(context,5,15,15);
    }

    /**
     * @param connectTimeout 连接超时（秒钟）
     */
    public SyncOkHttp(Context context,int connectTimeout, int readTimeout, int writeTimeout) {
        this.context = context;
        client = new OkHttpClient.Builder().connectTimeout(connectTimeout, TimeUnit.SECONDS).readTimeout(readTimeout, TimeUnit.SECONDS).
                writeTimeout(writeTimeout, TimeUnit.SECONDS).build();
    }

    /**
     * OkHttp 请求自签名的https初始化
     *
     * @param connectTimeout
     * @param readTimeout
     * @param writeTimeout
     * @param sslSocketFactory
     * @param x509TrustManager
     */
    public SyncOkHttp(Context context,int connectTimeout, int readTimeout, int writeTimeout, SSLSocketFactory sslSocketFactory, X509TrustManager x509TrustManager) {
        this.context = context;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
        builder.readTimeout(readTimeout, TimeUnit.SECONDS);
        builder.writeTimeout(writeTimeout, TimeUnit.SECONDS);
        // 运行请求重定向
        builder.followRedirects(true);
        // https支持
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        builder.sslSocketFactory(sslSocketFactory, x509TrustManager);
        client = builder.build();

    }


    public String get(String url) {
        try {

            if (OkHttp.isPrintLog) {
                Log.d(OkHttp.TAG, "网络请求开始：" + url);
            }

            Request request = new Request.Builder().url(url).build();
            Call call = client.newCall(request);
            Response response = call.execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                if (OkHttp.isPrintLog) {
                    Log.d(OkHttp.TAG, "网络请求成功：" + result);
                }
                return result;
            }else {
                if (OkHttp.isPrintLog) {
                    Log.d(OkHttp.TAG, "网络请求失败" + response.code());
                }
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (OkHttp.isPrintLog) {
            Log.d(OkHttp.TAG, "网络请求失败：" + 0);
        }
        return null;
    }

    public String post(String url, MediaType mediaType, String body) {
        return post(url, null, mediaType, body);
    }

    /**
     * post请求 (同时能请求很多个) 自定义
     *
     * @param url       请求url
     * @param headerMap
     * @param mediaType
     * @param body
     * @return
     */
    public String post(String url, Map<String, Object> headerMap, MediaType mediaType, String body) {

        try {

            if (OkHttp.isPrintLog) {
                Log.d(OkHttp.TAG, "网络请求开始：" + url);
            }

            Request.Builder requestBuilder = new Request.Builder();
            requestBuilder.url(url);
            if (headerMap != null) {
                for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
                    requestBuilder.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
                }
            }
            RequestBody requestBody = RequestBody.create(mediaType, body);
            requestBuilder.post(requestBody);
            Request request = requestBuilder.build();

            Call call = client.newCall(request);

            Response response = call.execute();
            if (response.isSuccessful()) {
                String result = response.body().string();

                if (OkHttp.isPrintLog) {
                    Log.d(OkHttp.TAG, "网络请求成功：" + result);
                }

                return result;
            }else {
                if (OkHttp.isPrintLog) {
                    Log.d(OkHttp.TAG, "网络请求失败" + response.code());
                }
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (OkHttp.isPrintLog) {
            Log.d(OkHttp.TAG, "网络请求失败：" + 0);
        }

        return null;
    }

    public String post(String url, Map<String, Object> paramMap) {
        try {

            if (OkHttp.isPrintLog) {
                Log.d(OkHttp.TAG, "网络请求开始：" + url);
            }

            FormBody.Builder builder = new FormBody.Builder();
            if (paramMap != null) {
                for (Map.Entry entry : paramMap.entrySet()) {
                    builder.add(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
                }
            }

            Request request = new Request.Builder().url(url).post(builder.build()).build();
            Call call = client.newCall(request);

            Response response = call.execute();
            if (response.isSuccessful()) {
                String result = response.body().string();

                if (OkHttp.isPrintLog) {
                    Log.d(OkHttp.TAG, "网络请求成功：" + result);
                }

                return result;
            }else {
                if (OkHttp.isPrintLog) {
                    Log.d(OkHttp.TAG, "网络请求失败" + response.code());
                }
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (OkHttp.isPrintLog) {
            Log.d(OkHttp.TAG, "网络请求失败：" + 0);
        }

        return null;
    }

    public String uploadFile(String url, Map<String, Object> paramMap, String fileName, File file) {

        try {
            MultipartBody.Builder builder = new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);

            if (paramMap != null) {
                for (Map.Entry entry : paramMap.entrySet()) {
                    builder.addFormDataPart(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
                }
            }

            if (file != null && file.exists()) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
                builder.addFormDataPart(fileName, file.getName(), requestBody);
            }

            Request request = new Request.Builder().url(url).post(builder.build()).build();
            Call call = client.newCall(request);

            Response response = call.execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                return result;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

}
